package com.zhangxiaofanfan.hotcode.first;

import java.util.Stack;

/**
 *
 *
 * @date 2024-06-29 03:21:25
 * @author zhangxiaofanfan
 */
public class HotCode071 {
    public static void main(String[] args) {
        HotCode071 hotCode = new HotCode071();
        String s = "3[a2[c]]";
        System.out.println(hotCode.decodeString(s));
    }

    public String decodeString(String s) {
        if (s == null || s.isEmpty()) {
            return "";
        }
        Stack<String> stack = new Stack<>();
        Stack<String> temp = new Stack<>();
        StringBuilder stringBuffer, integerBuffer, result = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != ']') {
                stack.push(s.charAt(i) + "");
                continue;
            }
            // 获取字符串
            while (!stack.isEmpty() && !stack.getLast().equals("[")) temp.add(stack.pop());
            stringBuffer = new StringBuilder();
            while (!temp.isEmpty()) stringBuffer.append(temp.pop());
            stack.pop();
            // 获取数字
            integerBuffer = new StringBuilder();
            while (!stack.isEmpty() && Character.isDigit(stack.getLast().charAt(0))) temp.add(stack.pop());
            while (!temp.isEmpty()) integerBuffer.append(temp.pop());
            // 构建字符
            stack.push(String.valueOf(stringBuffer).repeat(Math.max(0, Integer.parseInt(integerBuffer.toString()))));
        }
        while (!stack.isEmpty()) temp.add(stack.pop());
        while (!temp.isEmpty()) result.append(temp.pop());
        return result.toString();
    }
}
